#include "utils.h"


namespace hps {

uint64_t GetCurrentMS() {
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return tv.tv_sec * 1000ul + tv.tv_usec / 1000;
}

std::string TimeFormat(uint64_t time) {
    time_t _time = time / 1000;
    std::tm *gmtm = std::gmtime(&_time);

    // 格式化时间为字符串
    char buffer[80];
    std::strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", gmtm);
    return std::string(buffer);
}

QString loadStyle(const QString &filePath) {
    QFile file(filePath);
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        return file.readAll();
    } else {
        std::cerr << "Failed to open style file!" << std::endl;
    }
    return "";
}

bool isDirectoryExists(const std::string &path) {
    struct stat info;
    if (stat(path.c_str(), &info) != 0) {
        return false;
    }
    return (info.st_mode & S_IFDIR) != 0;
}
void loadStyle(QWidget *widget, QString path) {
    // 加载样式表文件
    QFile styleFile(path); // 使用资源文件

    if (styleFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QString styleSheet = styleFile.readAll();
        widget->setStyleSheet(styleSheet);
        styleFile.close();
    } else {
        qWarning("Failed to load style sheet.");
    }
}

std::string system(const char *cmd) {
    char buffer[128];
    std::string result = "";
    FILE *pipe = popen(cmd, "r");
    if (! pipe) {
        std::cerr << "Error: popen() failed!" << std::endl;
        return result;
    }
    while (fgets(buffer, sizeof(buffer), pipe) != nullptr) {
        result += buffer;
    }
    pclose(pipe);
    return result;
}
std::string getNameFromDir(const std::string& dir) {
    int idx = dir.size() - 1;
    if (dir.back() == '/')
        idx --;

    while (dir[idx] != '/')
        idx --;

    return dir.substr(idx + 1);
}

std::string getDirFromFilePath(const std::string& filePath) {
    if (filePath.find('.') == std::string::npos) {
        std::cerr << "FilePath isn't a file path." << std::endl;
        return "";
    }

    int cnt = 0, idx = filePath.size() - 1, l = -1, r = -1;
    while (idx >= 0 && cnt != 2) {
        if (filePath[idx] == '/' && cnt == 0) {
            r = idx;
            cnt ++;
            idx --;
            continue;
        }
        if (filePath[idx] == '/' && cnt == 1) {
            l = idx;
            cnt ++;
            break;
        }
        idx --;
    }

    int len = r - l - 1;
    std::string dirName = filePath.substr(l + 1, len);
    return dirName;
}
}